
package briefkeys;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.sql.*;
import java.util.*;

public class LogIn extends javax.swing.JFrame {
    static Runtime draobyek = Runtime.getRuntime();
    static Scanner keyboard = new Scanner(System.in);
    static String lockedName = "";
    static String runCmd = "cmd.exe";
    static String workingDir = "D:\\briefkeys\\";
        
    Connection con = null; 
    ResultSet rs = null;
    PreparedStatement ps = null;
    
    public LogIn() {
        con = Connector.ConnectDB();
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFrame1 = new javax.swing.JFrame();
        jFrame2 = new javax.swing.JFrame();
        jFrame3 = new javax.swing.JFrame();
        splashScreen1 = new briefkeys.SplashScreen();
        usernameText = new javax.swing.JTextField();
        passwordText = new javax.swing.JPasswordField();
        loginSmall = new javax.swing.JLabel();
        lableUsername = new javax.swing.JLabel();
        lableUsername1 = new javax.swing.JLabel();
        cancelButton = new javax.swing.JButton();
        unlockButton = new javax.swing.JButton();
        lockButton = new javax.swing.JButton();

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jFrame2Layout = new javax.swing.GroupLayout(jFrame2.getContentPane());
        jFrame2.getContentPane().setLayout(jFrame2Layout);
        jFrame2Layout.setHorizontalGroup(
            jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame2Layout.setVerticalGroup(
            jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jFrame3Layout = new javax.swing.GroupLayout(jFrame3.getContentPane());
        jFrame3.getContentPane().setLayout(jFrame3Layout);
        jFrame3Layout.setHorizontalGroup(
            jFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame3Layout.setVerticalGroup(
            jFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("BriefKeys | Log In");
        setAlwaysOnTop(true);
        setUndecorated(true);
        setResizable(false);

        usernameText.setFont(new java.awt.Font("Courier New", 0, 24)); // NOI18N
        usernameText.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        passwordText.setFont(new java.awt.Font("Courier New", 0, 24)); // NOI18N
        passwordText.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        loginSmall.setIcon(new javax.swing.ImageIcon(getClass().getResource("/briefkeys/log-in-small.png"))); // NOI18N
        loginSmall.setToolTipText("");

        lableUsername.setFont(new java.awt.Font("Courier New", 0, 24)); // NOI18N
        lableUsername.setText("USERNAME");

        lableUsername1.setFont(new java.awt.Font("Courier New", 0, 24)); // NOI18N
        lableUsername1.setText("PASSWORD");

        cancelButton.setBackground(new java.awt.Color(255, 0, 0));
        cancelButton.setFont(new java.awt.Font("Courier New", 0, 24)); // NOI18N
        cancelButton.setForeground(new java.awt.Color(255, 255, 255));
        cancelButton.setText("CANCEL");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        unlockButton.setBackground(new java.awt.Color(255, 255, 0));
        unlockButton.setFont(new java.awt.Font("Courier New", 0, 24)); // NOI18N
        unlockButton.setText("UNLOCK");
        unlockButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                unlockButtonActionPerformed(evt);
            }
        });

        lockButton.setBackground(new java.awt.Color(0, 255, 0));
        lockButton.setFont(new java.awt.Font("Courier New", 0, 24)); // NOI18N
        lockButton.setText("LOCK");
        lockButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                lockButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(loginSmall)
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lableUsername)
                    .addComponent(lableUsername1))
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(usernameText, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(passwordText, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lockButton, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(unlockButton, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(loginSmall)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(lableUsername)
                        .addGap(42, 42, 42)
                        .addComponent(lableUsername1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(usernameText, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(20, 20, 20)
                        .addComponent(passwordText, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(unlockButton, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lockButton, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        BriefKeys.main.setEnabled(true);
        this.dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    static String username;
    static String password;
    
    private void unlockButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_unlockButtonActionPerformed
        username = usernameText.getText().trim();
        password = passwordText.getText().trim();
      
        if(password.equals("") || username.equals("")) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Warning().setVisible(true);
                }
            });
        } else {
            String sql = "SELECT * FROM Accounts WHERE username=? AND password=?";
       
            try {
            
                ps = con.prepareStatement(sql);
                ps.setString(1, usernameText.getText());
                ps.setString(2, passwordText.getText());

                rs = ps.executeQuery();
                
                File file = new File(workingDir + username);
            
                if (rs.next()) {
                    if (!file.exists()) {
                        unlockMe(username);
                        unlockMe(username);
                        unlockMe(username);
                        unlockMe(username);
                        unlockMe(username);
                    
                        java.awt.EventQueue.invokeLater(new Runnable() {
                            public void run() {
                                new Unlock().setVisible(true);
                            }
                        });
                        
                    } else {
                        java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            new FileUnlocked().setVisible(true);
                        }
                    });
                    }
                    
                    
                } else if(rs.next() && file.exists()) {
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            new FileUnlocked().setVisible(true);
                        }
                    });
                } else if(rs.next()) {
                    String sql2 = "SELECT * FROM Accounts WHERE password=?"; 
                    ps = con.prepareStatement(sql2);
                    
                    usernameText.repaint();
                    passwordText.repaint();
               
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            new ErrorMessage().setVisible(true);
                        }
                    });
                    
                } else {
                    usernameText.repaint();
                    passwordText.repaint();
                    
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            new ErrorMessage().setVisible(true);
                        }
                    });
                }
             } catch (Exception e) {
            
             }finally {
                try {
                    rs.close();
                    ps.close();
                } catch(Exception e) {
                    
                }
            }
        }
    }//GEN-LAST:event_unlockButtonActionPerformed

    private void lockButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lockButtonActionPerformed
        username = (usernameText.getText().trim());
        password = passwordText.getText().trim();
        
        
      
        if(password.equals("") || username.equals("")) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Warning().setVisible(true);
                }
            });
        } else {
            String sql = "SELECT * FROM Accounts WHERE username=? AND password=?";
       
            try {
                ps = con.prepareStatement(sql);
                ps.setString(1, usernameText.getText());
                ps.setString(2, passwordText.getText());

                rs = ps.executeQuery();
                
                File file = new File(workingDir + username);
                
                if(rs.next()) {
                    if (file.exists()) {
                        lockMe(username);
                        lockMe(username);
                        lockMe(username);
                        lockMe(username);
                        lockMe(username);
                        lockMe(username);
                    
                        java.awt.EventQueue.invokeLater(new Runnable() {
                            public void run() {
                                new Lock().setVisible(true);
                            }
                        });
                        
                    } else {
                        java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            new FileExistsLock().setVisible(true);
                        }
                    });
                    }
                } else if(rs.next() && !file.exists()){
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            new FileExistsLock().setVisible(true);
                        }
                    });
                } else if(rs.next()) {
                    String sql2 = "SELECT * FROM Accounts WHERE password=?"; 
                    ps = con.prepareStatement(sql2);
                    
                    usernameText.repaint();
                    passwordText.repaint();
               
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            new ErrorMessage().setVisible(true);
                        }
                    });
                    
                } else {
                    usernameText.repaint();
                    passwordText.repaint();
                    
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            new ErrorMessage().setVisible(true);
                        }
                    });
                }
             } catch (Exception e) {
            
             } finally {
                try {
                    rs.close();
                    ps.close();
                } catch(Exception e) {
                    
                }
             }
        }
    }//GEN-LAST:event_lockButtonActionPerformed
    
    public static void unlockMe(String dir) throws Exception {
		/* Unlocking */
        lockedName = "Control Panel.{" + dir + "}";
    	draobyek.exec(new String[]{runCmd, "/c", "attrib", "-h", "-s", workingDir+lockedName});
        do {
            draobyek.exec(new String[]{runCmd, "/c", "ren", (workingDir+lockedName), dir});
            draobyek.exec(new String[]{runCmd, "/c", "ren", (workingDir+lockedName), dir});
        } while ((lockedName).equals(dir));
    }

    public static void lockMe(String dir) throws Exception {
		/* Locking */
        lockedName = "Control Panel.{" + dir + "}";
    	draobyek.exec(new String[]{runCmd, "/c", "ren", (workingDir+dir), lockedName});
    	draobyek.exec(new String[]{runCmd, "/c", "attrib", "+h", "+s", workingDir+lockedName});
    }
    
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LogIn().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JFrame jFrame2;
    private javax.swing.JFrame jFrame3;
    private javax.swing.JLabel lableUsername;
    private javax.swing.JLabel lableUsername1;
    private javax.swing.JButton lockButton;
    private javax.swing.JLabel loginSmall;
    private javax.swing.JPasswordField passwordText;
    private briefkeys.SplashScreen splashScreen1;
    private javax.swing.JButton unlockButton;
    private javax.swing.JTextField usernameText;
    // End of variables declaration//GEN-END:variables
}
